<template>
  <div>
    <!-- 员工选择（根据组织id） -->
    <a-select
      v-bind="$attrs"
      v-on="$listeners"
      :placeholder="placeholder"
      :optionFilterProp="optionFilterProp"
      v-model="currentValue"
      allowClear
    >
      <a-icon v-if="fetching" style="color: #096dd9" slot="suffixIcon" type="loading" />
      <a-spin v-if="fetching" slot="notFoundContent" size="small" />
      <a-select-option v-for="i in list" :key="i.id" :value="i.id">{{
        !customRender ? i.name : customRender(i)
      }}</a-select-option>
    </a-select>
  </div>
</template>
<script>
import { getOrgEmployeesListBy } from '@/api/commons'

export default {
  inheritAttrs: false,
  name: 'SelectOrgPeople',
  props: {
    // v-model绑定的数据
    value: {
      type: [Array, String, Object],
    },
    // 组织id
    id: [String, Number, Object],
    // false:直属组织ID;true:组织ID及其下级组织
    isRoot: {
      type: Boolean,
      default: () => true,
    },
    // placeholder
    placeholder: {
      type: String,
      default: () => '请选择',
    },
    // 搜索时过滤对应的 option 属性，如设置为 children 表示对内嵌内容进行搜索,否则为value
    optionFilterProp: {
      type: String,
      default: () => 'children',
    },
    // 是否初始化
    init: {
      type: Boolean,
      default: () => false,
    },
    // 自定义name
    customRender: {
      type: [Function],
      default: null,
    },
  },
  data() {
    return {
      fetching: false,
      list: [],
    }
  },
  watch: {
    id(e) {
      this.getList()
    },
  },
  mounted() {
    this.init && this.getList()
  },
  methods: {
    getList() {
      let params = {}
      params[this.isRoot ? 'rootOrgId' : 'orgId'] = this.id
      this.fetching = true
      getOrgEmployeesListBy(params)
        .then((res) => {
          this.fetching = false
          this.list = res.data
        })
        .catch((res) => {
          this.fetching = false
        })
    },
  },
  computed: {
    // 转换绑定的选中数据，与v-model同步
    currentValue: {
      get: function () {
        return this.value || void 0
      },
      set: function (value) {
        this.$emit('input', value)
      },
    },
  },
}
</script>
